<?php
/**
 * Created by PhpStorm.
 * User: chenxiaogang
 * Date: 2017/11/9
 * Time: 上午11:08
 */

namespace User\Model;

use Common\Model\CommonModel;
use Common\Lib\Curl;
use Common\Lib\Redis\Redis;

class OverdueRecord extends CommonModel
{
    const IS_ZERO = 0;//为0
    const SUCCESS = 1;//表示成功，用于status=1表判断
    const FAILURE = 0;//表示失败，用于status=0表判断

    protected $connection = 'DB_CONFIG2';
    protected $trueTableName = 'jinjiedao_overdue_record';

    /**
     * @use          [获取用户信息]
     * @author       chenxiaogang
     * @param null $user_id
     * @return array
     */
    public function getJjdInfo($user_id = null)
    {
        if(empty( $user_id )) {//判断是否传入了用户ID
            return [ 'status' => self::FAILURE, 'message' => '请传入用户ID' ];
        }
        $count = M( 'User', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => (int)$user_id ] )->count( 'id' );
        //var_dump(M( 'User', 'system_', C( 'DB_CONFIG2' ) )->_sql());die;
        if(!($count > 0)) {//判断是否存在该客户
            return [ 'status' => self::FAILURE, 'message' => '该客户不存在' ];
        }
        $data = $this->where( [ 'user_id' => $user_id ] )->find();
        if(empty( $data )) {
            $data = $this->refreshJjdInfo( $user_id );
            if($data['status'] === self::SUCCESS) {
                return [ 'status' => self::SUCCESS, 'message' => $data['message'], 'data' => $data['data'] ];
            }
            return [ 'status' => self::FAILURE, 'message' => $data['message'] ];
        } else {
            //将我方平台的信息回调给今借到
            //$this->callbackUserInfoTojinjiedao( $user_id, $data );
            return [ 'status' => self::SUCCESS, 'message' => '从库中取出', 'data' => $data ];
        }
    }

    /**
     * @use          [通过今借到接口获取用户信息]
     * @author       chenxiaogang
     * @param $user_id
     * @return array
     */
    public function refreshJjdInfo($user_id)
    {
        //做一下缓存，防止多个用户频繁点击该按钮
        $redis = Redis::getInstance();
        $id = I( 'request.id', 0 );
        $key = C( 'USER_JJD_REPORT_REDIS_KEY_PREFIX' ) . $id;
        if($redis->exists( $key )) {
            return [ 'status' => self::SUCCESS, 'message' => '信用数据查询成功2', 'data' => $redis->hGetAll( $key ) ];
        } else {
            $find = M( 'user', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => (int)$user_id ] )->field( 'name,mobile,identity' )->find();
            $post = [
                'name' => $find['name'],
                'telephone' => $find['mobile'],
                'cardId' => $find['identity'],
                'platform' => C( 'USER_JJD_REPORT_API_PLATFORM' ),
            ];
            $url = C( 'USER_JJD_REPORT_API_URL' );
            $curl = new Curl();
            $data = json_encode( $post );
            $curl->setOption( CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ] );
            $res = $curl->post( $url, $data );
            $resData = json_decode( $res, true );
            if(!isset( $resData['code'] ) || ($resData['code'] != 200)) {
                return [ 'status' => self::FAILURE, 'message' => isset( $resData['message'] ) ? $resData['message'] : (string)$res ];
            }
            $finalData = array_merge( [ 'user_id' => $user_id ], $resData['object']['creditInfo'] );
            $finalData['flag'] = 1;
            //var_dump($finalData);die;
            //如果找不到就新增，否则更新//入mysql
            $count = $this->where( [ 'user_id' => $user_id ] )->count( 'jjd_id' );
            if(!($count > 0)) {
                $this->add( $finalData );
            } else {
                $this->where( [ 'user_id' => $user_id ] )->save( $resData['object']['creditInfo'] );
            }
            $redis->hMset( $key, $finalData );//入redis
            $redis->expire( $key, 60 );//60秒过期
            //将我方平台的信息回调给今借到
            $this->callbackUserInfoTojinjiedao( $user_id, $finalData );
            return [ 'status' => self::SUCCESS, 'message' => $resData['message'], 'data' => $resData['object']['creditInfo'] ];
        }
    }

    /**
     * @use          [将用户信息回调给今借到]
     * @param       $user_id   [用户ID]
     * @param       $finalData [金额借到接口返回的用户信息信息]
     * @author       chenxiaogang
     */
    private function callbackUserInfoTojinjiedao($user_id, $finalData)
    {
        $url = C( 'USER_JJD_CALLBACK_API_URL' );
        $ordersModel = new Orders();
        $ordersSubModel = new OrdersSub();
        $logsModel = new Log();
        $borrow = $ordersModel->getBorrow( $user_id );
        $overdue = $logsModel->getOverdue( $user_id );
        $daysOd = $logsModel->getDaysOverdue( $user_id );
        $data = [
            'c_name' => $finalData['c_name'],
            'id' => $finalData['id'],
            'c_telephone' => $finalData['c_telephone'],
            'c_id_card_no' => $finalData['c_id_card_no'],
            'c_platform_name' => $finalData['c_platform_name'],
            'n_current_overdue_amt' => $ordersSubModel->getCurrentOverdueAmt( $user_id ),//当前逾期金额
            'n_history_overdue_max' => $logsModel->getMaxOverdueAmt( $user_id ),//最大逾期金额
            'n_current_overdue_7days_amt' => $daysOd['overdue_7days_amt'],//>7 天逾期金额
            'n_current_overdue_7days_cnt' => $daysOd['overdue_7days_cnt'],//>7 天逾期笔数
            'n_overdue_30days_amt' => $daysOd['overdue_30days_amt'],//>30 天逾期金
            'n_overdue_30days_cnt' => $daysOd['overdue_30days_cnt'],//>30 天逾期笔数
            'n_overdue_90days_amt' => $daysOd['overdue_90days_amt'],//>90 天逾期金 额
            'n_overdue_90days_cnt' => $daysOd['overdue_90days_cnt'],//>90 天逾期笔 数
            'n_borrow_cn' => $borrow['leiji_count'],//累计借入笔数
            'n_borrow_amt' => $borrow['leiji_amount'],//累计借入金额
            'n_overdue_amt' => $overdue['over_due_amount'],//累计逾期金额
            'n_overdue_cnt' => $overdue['over_due_count'],//累计逾期次数
            'flag' => 1,
        ];
        //var_dump($data);die;
        //传过去
        $curl = new Curl();
        $post = json_encode( $data );
        $curl->setOption( CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ] );
        $res = $curl->post( $url, $post );
        //'{"code":200,"object":null,"message":"信用数据接收成功"}'
        //echo $res;die;
        //echo '<meta charset="utf-8">';
        //var_dump($res);die;
    }

}